<?php
namespace Admin\Model;

use Common\Model\CommonModel;

class RefundModel extends CommonModel {
	protected $softdelete = false;
	protected $deleteTime = 'delete_time';

	public function get_sale_manager_list($where = array(),$order = '',$from =  0,$to = 0){
		$list = $this->alias("r")->field("r.*,m.sale_manage_name,u.user_nicename,u.user_phone")->where($where)
				->join("bdt_sale_manager m ON m.id = r.rid","LEFT")
				->join("bdt_users u ON u.id = r.uid","LEFT")
				->order($order)
				->limit($from , $to)
				->select();
		return $list;
	}

	/**
	 * 退款记录
	 * $model = 1 上级消费机构退款  =2 卡退款
	 * -1 参数有误
	 * -2 金额有误
	 * -3 数据为空
	 * -4 数据插入失败
	 * -5 金额不足
	 */
	public function insert_data($insert,$model){
		$rid = $insert["rid"];
		if(empty($rid)){	//参数有误
			return -1;
		}
		$price = $insert["price"];	//退款金额
		if(!(!empty($price) && is_numeric($price) && $price>0)){	//退款金额输入有误
			return -2;
		}
		$insert["number"] = date("YmdHis").rand(10000,99999);
		$insert["uid"] = session("ADMIN_ID");
		$insert["create_time"] = time();
		$insert["model"] = $model;

		if($model == 1){
			$item = M("SaleManager")->where(array("id"=>$rid))->find();

		}elseif($model == 2){
			$item = M("Card")->where(array("id"=>$rid))->find();
			$insert["lid"] = $insert["lid"]?$insert["lid"]:$item["lid"];
		}else{
			return -1;
		}

		if(empty($item)){
			return -3;
		}
		if($price>$item["balance"]){
			return -5;
		}
		$insert["before_balance"] = $item["balance"];
		$insert["after_balance"] = $item["balance"]-$price;
		$result = $this->add($insert);
		if($result){
			if($model == 1){
				// M("SaleManager")->where(array("id"=>$rid))->setDec("balance",$price);
                $result = D("Admin/SaleManagerBill")->insert_data($rid, $price, 2);
			}elseif($model == 2){
				$result = M("Card")->where(array("id"=>$rid))->setDec("balance",$price);
				if($item["lid"]>0 && $result){
					D("Logistics/LogisticsBill")->insert_data($item["lid"],$price,8);
				}
			}
			return true;
		}else{
			return -4;
		}


	}
}